package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.server.config.TanHuaDefaultConfig;
import com.tanhua.server.config.TanHuaSSOConfig;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class TodayBestService {

    @Autowired
    private UserService userService;

//    @Value("${tanhua.sso.default.user}")
//    private Long defaultUser;
    @Autowired
    private TanHuaSSOConfig defaultUser;

    @Autowired
    private TanHuaDefaultConfig defaultRecommendUsers;

    @DubboReference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    private TodayBest todayBestMy;

    public TodayBest queryTodayBest() {
        //校验token,获取userId
        Long userId = UserThreadLocal.get();
        //通过调用dubbo服务查询得分最高的用户
        RecommendUser recommendUser = this.recommendUserApi.queryWithMaxScore(userId);
        if (ObjectUtil.isEmpty(recommendUser)) {
            //给出一个默认的推荐用户
            recommendUser = new RecommendUser();
            recommendUser.setToUserId(userId);
            recommendUser.setUserId(defaultUser.getUser());
            //随机一个得分
            recommendUser.setScore(RandomUtil.randomDouble(80, 100));
        }
        //根据用户id查询用户的基本信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(recommendUser.getUserId());
        TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setId(userInfo.getUserId());
        todayBest.setFateValue(recommendUser.getScore().longValue());
        todayBestMy = todayBest;

        return todayBest;
    }

    /**
     * 查询推荐用户列表
     *
     * @param queryParam
     * @return
     */
    public PageResult queryRecommendation(RecommendUserQueryParam queryParam) {
        //校验token，获取userId
        Long userId = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());
        //查询dubbo服务,查询推荐列表
        PageInfo<RecommendUser> pageInfo = this.recommendUserApi.queryPageInfo(userId, queryParam.getPage(), queryParam.getPagesize());
        List<RecommendUser> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            List<String> userIdList = StrUtil.split(defaultRecommendUsers.getUsers(), ',');
            records = new ArrayList<>();

            for (String uid : userIdList) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setToUserId(userId);
                recommendUser.setUserId(Convert.toLong(uid));
                // 随机得分
                recommendUser.setScore(RandomUtil.randomDouble(80, 99));
                records.add(recommendUser);
            }
            //不建议返回null
//            return pageResult;
        }
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoApi.queryByRecommendUser(userIdList, queryParam.getAge(), queryParam.getCity());
        if (CollUtil.isEmpty(userInfoList)) {
            return pageResult;
        }
        //目标：封装TodayBest列表
        ArrayList<TodayBest> todayBestList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setId(userInfo.getUserId());
            //查找到该用户所对应的RecommUser对象，目的是获取他的得分
            for (RecommendUser record : records) {
                if (ObjectUtil.equal(record.getUserId(), userInfo.getUserId())) {
                    todayBest.setFateValue(record.getScore().longValue());
                    break;
                }
            }
            todayBestList.add(todayBest);
        }
        //对集合排序
        Collections.sort(todayBestList, (o1, o2) -> Convert.toInt(o2.getFateValue() - o1.getFateValue()));
        // 排除今日佳人的用户
//        todayBestList.remove(0);
        for (int i = 0; i < todayBestList.size(); i++) {
            Long id = todayBestList.get(i).getId();
            if (ObjectUtil.equal(id, todayBestMy.getId())) {
                todayBestList.remove(i);
            }
        }

        pageResult.setItems(todayBestList);
        return pageResult;
    }
}
